<template>
  <div>
    <!-- 查询 --> 
    <el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top: 20px">
      <!-- 重置会看 el-form-item 组件元素的 prop 上是否指定了字段名，指定了才会重置生效 -->
      <el-form-item prop="name">
        <el-input v-model="searchMap.name" placeholder="用户名字" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item prop="deptId" label="请选择部门">
        <!-- <el-input v-model="searchMap.deptId" placeholder="部门id" style="width: 200px"></el-input> -->
        <el-cascader
          v-model="searchMap.deptId"
          :options="costData"
          :show-all-levels="false"
          :props="{ checkStrictly: true, emitPath: false }"
          clearable
          filterable
          @change="changeDeptId"
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button @click="resetForm('searchForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="list" height="600" border style="width: 100%">
      <!-- type="index"获取索引值，从1开始 ，label显示标题，prop 数据字段名，width列宽 -->
      <el-table-column type="index" label="序号" width="150"></el-table-column>
      <el-table-column prop="name" label="用户名字" width="200"></el-table-column>
      <el-table-column prop="dept.name" label="所属部门" width="200"></el-table-column>
      <el-table-column prop="imgUrl" label="用户图片" align="center">
        <template scope="scope">
          <el-image :src="scope.row.imgUrl" style="width: 100px;height:100px;margin-left:10px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button size="mini" @click="handleSignin(scope.row.id)">签到记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchMap.page"
      :page-sizes="[10, 20, 50]"
      :page-size="searchMap.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 弹出新增窗口 
        title 窗口的标题
        :visible.sync 当它true的时候，窗口会被弹出
    -->
    <el-dialog title="用户编辑" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        ref="pojoForm"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        :model="pojo"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="pojo.name"></el-input>
        </el-form-item>

        <el-form-item prop="deptId" label="请选择部门">
          <!-- <el-input v-model="searchMap.deptId" placeholder="部门id" style="width: 200px"></el-input> -->
          <el-cascader
            v-model="pojo.deptId"
            :options="costData"
            :show-all-levels="false"
            :props="{ checkStrictly: true, emitPath: false }"
            clearable
            filterable
            @change="changeDeptId"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="用户图片" prop="img64">
          <el-upload
            action
            :on-change="getFile"
            :limit="1"
            list-type="picture"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">选择图片上传,最多上传一张图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="addData('pojoForm')">确 定</el-button> -->
        <el-button
          type="primary"
          @click="pojo.id === null ? addData('pojoForm'): updateData('pojoForm')"
        >确 定</el-button>
      </div>
    </el-dialog>

    <!-- 用户的签到记录 -->
    <el-dialog title="用户的签到记录" :visible.sync="dialogPersonsigninVisible" width="800px">
     <div>
        <div>应该签到的次数:  {{this.count}}</div>
        <div>缺勤次数:  {{this.noSignin}}</div>
        <div>出勤率:{{saveTwo(this.signinRate)*100+'%'}}</div>
        <el-table
            :data="person_list"
            height="600"
            border
            style="width: 100%">
    
            <el-table-column type="index" label="序号" width="150"></el-table-column>
            <el-table-column prop="signin.name" label="签到名字" width="200"></el-table-column>
            <el-table-column prop="signin.startTime" label="开始时间" ></el-table-column>
            <el-table-column prop="signin.endTime" label="结束时间" ></el-table-column>
            <el-table-column prop="signinTime" label="状态" width="200" >
                <template slot-scope="scope">
                    <span>{{scope.row.signinTime==null?'未签到':"签到成功"}}</span><br>
                    <span>{{scope.row.signinTime==null?'':""+scope.row.signinTime}}</span>
                </template>
            </el-table-column>

        </el-table>
    </div>
    </el-dialog>
  </div>
</template>
<script>
import personApi from "@/api/person";
// import Personsignin from "@/views/personsignin";
import personsigninApi from '@/api/personsignin'


export default {
  // components: { Personsignin },

  data() {
    return {
      list: [],
      total: 0, // 总记录数
      //curent: 1,
      //size: 5,
      //currentPage: 1, // 当前页码
      //pageSize: 20, // 每页显示10条数据,
       person_list: [],
            count: 0,
            noSignin: 0,
            signinRate: 0,
      searchMap: {
        // 条件查询绑定的条件值
        deptId: null,
        name: null,
        page: 1,
        size: 10
      },
      dialogFormVisible: false, //控制对话框
      pojo: {
        id: null,
        name: null,
        deptId: null,
        img64: null
      }, // 提交的数据
      costData: [], //部门下拉数据
      dialogPersonsigninVisible: false, //用户的签到记录
      personId: 0 //给子组件的值
    };
  },

  created() {
    this.fetchData();
    this.getDepartment();
  },

  methods: {
    // 获取所有部门数据
    getDepartment() {
      personApi.getDepartment().then(res => {
        this.costData = this.formatJson(res.data.data);
        console.log("---res---", res.data);
      });
    },
    //将多维数组转换为el-cascader识别的数组格式{value:'',name:'',children:[]}
    formatJson(data) {
      return data.map(t => {
        if (t.children.length > 0) {
          //如果有子节点时将重组子节点中的数据
          return {
            value: t.id,
            label: t.name,
            children: this.formatJson(t.children)
          };
        } else {
          return { value: t.id, label: t.name };
        }
      });
    },
    changeDeptId(id) {
      this.searchMap.deptId == id;
      console.log("---666---", id, this.searchMap.deptId);
    },
      // 获取签到列表
    	fetchDataList(){
        personsigninApi.search(this.personId).then(res=>{ 
					console.log('---签到记录列表---',this.personId,res) 
          const resp = res.data
          this.person_list = resp.data.list
          this.count = resp.data.count 
          this.noSignin = resp.data.noSignin
          this.signinRate = (this.count-this.noSignin)/this.count
            })
					},
      // 出勤率数据过滤处理
      saveTwo(num) {      
				return num.toFixed(2)    
			},

    getFile(file, fileList) {
      this.getBase64(file.raw).then(res => {
        this.pojo.img64 = res;
      });
    },
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    },

    fetchData() {
      personApi.search(this.searchMap).then(response => {
        const resp = response.data;
        // console.log(resp.data.rows)
        this.list = resp.data.list;
        this.total = resp.data.total;
      });
    },
    // 当每页显示条数改变后,被触发 , val是最新的每页显示条数
    handleSizeChange(val) {
      // console.log(val)
      this.searchMap.size = val;
      this.fetchData();
    },
    // 当页码改变后,被触发 , val 是最新的页面
    handleCurrentChange(val) {
      // console.log(val)
      this.searchMap.page = val;
      this.fetchData();
    },

    //重置
    resetForm(formName) {
      console.log("重置", formName);
      // 重置会看 el-form-item 组件元素的 prop 上是否指定了字段名，指定了才会重置生效
      this.$refs[formName].resetFields();
    },
    // 提交新增数据
    addData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //提交表单
          //console.log('addData')
          personApi.add(this.pojo).then(response => {
            const resp = response.data;
            if (resp.flag) {
              //新增成功，刷新列表数据
              this.fetchData();
              this.dialogFormVisible = false; // 关闭窗口
              this.$message({
                message: "添加成功",
                type: "success"
              });
            } else {
              // 失败，来点提示信息
              this.$message({
                message: resp.msg,
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    // 弹出新增窗口
    handleAdd() {
      console.log(this.pojo);
      // this.pojo = {}
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["pojoForm"].resetFields();
      });
    },

    // 打开编辑窗口
    handleEdit(id) {
      //console.log('编辑', id)
      this.handleAdd();
      personApi.getById(id).then(response => {
        const resp = response.data;
        if (resp.flag) {
          const img64t = this.pojo.img64;
          this.pojo = resp.data;
          this.pojo.img64 = img64t;
          //console.log(this.pojo)
        }
      });
    },

    updateData(formName) {
      //console.log('updateData')
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 提交更新
          console.log(this.pojo);
          personApi.update(this.pojo).then(response => {
            const resp = response.data;
            if (resp.flag) {
              // 刷新列表
              this.fetchData();
              this.dialogFormVisible = false;
              this.$message({
                message: "修改成功",
                type: "success"
              });
            } else {
              this.$message({
                message: resp.message,
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    // 删除会员
    handleDelete(id) {
      console.log("删除", id);
      this.$confirm("确认删除这条记录吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(() => {
          // 确认
          //console.log('确认')
          personApi.deleteById(id).then(response => {
            // console.log(response)
            const resp = response.data;

            this.$message({
              message: resp.message,
              type: resp.flag ? "success" : "error"
            });

            if (resp.flag) {
              // 删除成功，刷新列表数据
              this.fetchData();
              this.$message({
                message: "删除成功",
                type: "success"
              });
            }
          });
        })
        .catch(() => {
          // 取消，不用理会
          console.log("取消");
        });
    },
    //进入用户的签到记录
    handleSignin(id) {
      this.personId = id;
      this.dialogPersonsigninVisible = true;
      this.fetchDataList();
    }
  }
};
</script>

